﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace iTool.SQL.Analysis.FromClause
{
    public class SqlDerivedTableExpressionAnalysis : SqlAnalysisBase
    {
        public SqlDerivedTableExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            if (false & base.CodeObject is SqlDerivedTableExpression)
            {
                if (base.CodeObject?.Children.OfType<SqlQuerySpecification>().FirstOrDefault() != null)
                {
                    var derived = (SqlDerivedTableExpression)base.CodeObject;
                    var tables = ((SqlSelectAnalysisContext)base.context).QueryTables;
                    tables.Add(new SQLTableOptions
                    {
                        Alias = derived.Alias?.Value,
                        Name = $"$query_{tables.Count + 1}"
                    });
                }
            }
            else
            {
                base.context.Errors.Add("not support childs query: " + base.CodeObject.Sql + ",please use join mode.This will affect the efficiency of execution");
            }
            base.Next();
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
